<template>
  <AgGridVue :rowHeight="33" :headerHeight="33" @grid-ready="gridReady" @columnResized="onColumnResized"
    @click="AggridonClick" @columnMoved="onColumnMoved" @columnVisible="onColumnVisible"
    @SelectionChanged="onSelectionChanged" @FilterChanged="onFilterChanged" @sortChanged="sortChanged"
    style="height: 100%; width: 99%" :defaultColDef="{
      sortable: true, //可排序
      resizable: true, //可拖动改变列宽
      filter: true, //可过滤筛选
      editable: false, //是否可编辑
      // floatingFilter: true,
    }" class="ag-theme-alpine" :rowData="props.rowData" :columnDefs="computedColumn"
    :suppressCopyRowsToClipboard="true" :suppressDragLeaveHidesColumns="true" :localeText="props.localeText"
    :enableBrowserTooltips="true" :enableCellTextSelection="true" :tooltipMouseTrack="true"
    :suppressClipboardPaste="true" :tooltipShowDelay="100" :rowSelection="props.rowSelection"
    :suppressColumnVirtualisation="props.suppressColumnVirtualisation"
    :suppressRowVirtualisation="props.suppressRowVirtualisation"></AgGridVue>
</template>

<script lang="ts" setup>
import { withDefaults, onMounted, nextTick } from 'vue'
//表格
import { AgGridVue } from 'ag-grid-vue3'
import useAgGridFilterSelector from '@/utils/aggridFilterAllSelect'
import setAggridMinwidths from '@/utils/setAggridMinWidth'
import { saveOrUpdateGridState } from '@/hooks/useGridState'
import emitter from '@/hooks/useEventBus'
const aggridFs = useAgGridFilterSelector()
const props = withDefaults(
  defineProps<{
    rowData: any
    columnDefs: any
    localeText: any
    rowSelection: any
    suppressColumnVirtualisation: boolean
    suppressRowVirtualisation: boolean
    tableName: string
  }>(),
  {
    rowData: [],
    columnDefs: [],
    localeText: {},
    rowSelection: 'multiple',
    suppressColumnVirtualisation: false,
    suppressRowVirtualisation: false,
    tableName: undefined,
  }
)
const emit = defineEmits([
  'grid-ready',
  'columnResized',
  'click',
  'columnMoved',
  'columnVisible',
  'SelectionChanged',
  'FilterChanged',
])

const computedColumn = computed(() => {
  return setAggridMinwidths(props.columnDefs, gridOption)
})

const gridReadys = ref()
const colState = ref()
const gridOption = ref()
let saveGridState: Function
let updateGridState: Function
const gridReady = (params: any) => {
  const setRowDataCopy = params.api.setRowData
  gridOption.value = params.api
  colState.value = params.columnApi
  const { saveGridState: saveGridStateInfun, updateGridState: updateGridStateFun } = saveOrUpdateGridState(props.tableName, gridOption, colState, computedColumn.value)
  saveGridState = saveGridStateInfun
  updateGridState = updateGridStateFun
  updateGridState()
  function decorateFunction() {
    setTimeout(() => {
      try {

        if (colState && colState.value && colState.value.getColumns) {
          if (colState.value.getColumns().length == 0) return
          const allColumnIds = colState.value
            .getColumns()
            .map((column: { pinned: any; getId: () => any }) => {
              if (!column.pinned && column.getId()) {
                return column.getId()
              }
            })
          nextTick(() => {
            colState.value.autoSizeColumns(
              allColumnIds.filter((item: any) => item),
              false
            )
          })
        }
      } catch (error) {
        console.log(error)
      }
    }, 100)
  }
  function datasRowlet(val: any) {
    console.log(val.length)
    emitter.emit('lenghensssss', val.length)
  }
  params.api.setRowData = function (rowData: any) {
    setRowDataCopy.apply(this, arguments)
    // decorateFunction.apply(this, arguments)
    datasRowlet.apply(this, arguments)
    updateGridState()
    nextTick(() => {
      // 更新表头的最大行号
      let yourColumnDefs = gridOption.value.getColumnDefs();
      let rowIndexColumn = yourColumnDefs.find(colDef => colDef.colId === "ROW_INDECX");
      if (rowIndexColumn) {
        let maxNumberIndex = []
        gridOption.value.forEachNodeAfterFilter((row: any) => {
          maxNumberIndex.push(row)
        })
        rowIndexColumn.headerName = maxNumberIndex.length;
        gridOption.value.setColumnDefs(yourColumnDefs);
      }
    })
  }
  gridReadys.value = params.api
  emit('grid-ready', params)
}


const onColumnResized = () => {
  if (props.tableName && gridOption.value) {
    saveGridState()
  }
  emit('columnResized')
}
const AggridonClick = () => {
  emit('click')
}

const onColumnMoved = () => {
  if (props.tableName && gridOption.value) {
    saveGridState()
  }
  emit('columnMoved')
}

const onColumnVisible = () => {
  updateGridState()
  emit('columnVisible')
}
const onSelectionChanged = (params: any) => {
  aggridFs.clickAllSelectors(params)
  emit('SelectionChanged', params)
}

const onFilterChanged = (params: any) => {
  aggridFs.onFilterChanged(params)
  let dataList: any = []

  params.api.forEachNodeAfterFilter((row: any, index: number) => {
    dataList.push(row.data)
  })

  params.api.forEachNode((node, index) => {
    const rowIndex = index + 1;
    if (node.data.ROW_INDECX !== rowIndex) {
      node.setDataValue('ROW_INDECX', rowIndex);
    }
  });

  let yourColumnDefs = gridOption.value.getColumnDefs()
  // 找到行号列的配置对象
  let rowIndexColumn = yourColumnDefs.find(colDef => colDef.colId === "ROW_INDECX");
  // 如果找到了行号列的配置对象，则更新其 headerValue 属性为最大的 ROW_INDEX
  if (rowIndexColumn) {
    rowIndexColumn.headerName = dataList.length;
    gridOption.value.setColumnDefs(yourColumnDefs)
  }

  // LineNumber.value = dataList.length || 0
  // console.log(params)
  // emitter.emit('lenghensssss', dataList.length)
  emit('FilterChanged', params)
}


const sortChanged = (params) => {
  let dataList = [];
  let maxRowIndex = 0;

  // 遍历过滤后的节点，更新行号并收集数据
  params.api.forEachNodeAfterFilter((node, index) => {
    const rowIndex = index + 1;
    if (node.data.ROW_INDECX !== rowIndex) {
      node.setDataValue('ROW_INDECX', rowIndex);
    }
    dataList.push(node.data);
    maxRowIndex = Math.max(maxRowIndex, rowIndex);
  });

  // 更新表头的最大行号
  let yourColumnDefs = gridOption.value.getColumnDefs();
  let rowIndexColumn = yourColumnDefs.find(colDef => colDef.colId === "ROW_INDECX");
  if (rowIndexColumn) {
    rowIndexColumn.headerName = maxRowIndex;
    gridOption.value.setColumnDefs(yourColumnDefs);
  }
};
// watch(
//   () => props.rowData,
//   () => {
//     gridReadys.value.setRowData(props.rowData)
//     // setAggridMinwidths(colState.value.getColumnState())
//   }
// )

</script>
<style scoped>
:deep(.ag-header-group-cell) {
  border-right: 1px #babfc7 solid;
}

:deep(.arco-trigger-popup) {
  z-index: 10000 !important;
}

.arco-trigger-popup {
  z-index: 10000 !important;
}

:deep(.arco-trigger-popup) {
  z-index: 10000 !important;
}

:deep(.ag-cell),
:deep(.ag-header-cell) {
  border-right: 1px solid #dde2eb;
}

/* :deep(.ag-cell) {
  display: flex;
  align-items: center;
  justify-content: center;
} */

:deep(.ag-ltr .ag-selection-checkbox) {
  margin: 0 !important;
}
</style>
